package com.shj.service.impl;

import com.shj.dao.SysUserMapper;
import com.shj.dao.SysUserRoleMapper;
import com.shj.entity.SysUser;
import com.shj.entity.SysUserRole;
import com.shj.service.SysUserRoleService;
import com.shj.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *@Description TODO
 *@Author songhuajian
 *@Date 2020/1/7 15:57
 **/
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Override
    public List<SysUser> findAll() {
        return sysUserMapper.findAll();
    }

    /**
     * @description 根据userId查找用户
     * @author songhuajian
     * @date 2020/1/9 13:30
     */
    @Override
    public SysUser findByUserId(String userId){
        return sysUserMapper.selectByUserId(userId);
    }

    /**
     * @Description 添加用户
     * @author songhuajian
     * @date 2020/5/2 16:40
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(SysUser sysUser, List<String> roles) {
        // 添加用户角色
        String userId = sysUser.getUserId();
        sysUserRoleService.add(userId, roles);
        // 加密密码,添加用户
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String entryPwd = passwordEncoder.encode(sysUser.getPwd());
        sysUser.setPwd(entryPwd);
        return sysUserMapper.insert(sysUser);
    }

    /**
     * @Description 修改用户
     * @author songhuajian
     * @date 2020/5/2 16:41
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(SysUser sysUser, List<String> roles) {
        String userId = sysUser.getUserId();
        // 删除用户关联角色
        sysUserRoleService.delete(userId);
        // 添加用户角色
        sysUserRoleService.add(userId, roles);
        // 修改用户信息
        return sysUserMapper.update(sysUser);
    }

    /**
     * @Description 删除用户
     * @author songhuajian
     * @date 2020/5/2 16:41
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(String userId) {
        // 删除用户关联角色
        sysUserRoleService.delete(userId);
        // 删除用户
        return sysUserMapper.delete(userId);
    }

}
